package ext.tianma.part.processors;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import wt.fc.WTObject;
import wt.part.WTPart;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.wip.WorkInProgressHelper;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.core.CoreUtil;
import ext.tianma.part.forms.TransitFactoryUtil;

/**
 * 执行物料批量转厂
 * @author xxu
 *
 */
public class MassTransitFactoryProcessor extends DefaultObjectFormProcessor{
	private static final String RAWMATERIAL = "RawMaterial" ;
	private static List< String > viewlist = new ArrayList< String >();
	private static String[] facs ={"C01","C02","C04","C08"};
	static{
		
		viewlist.add("C01");
		viewlist.add("C02");
		viewlist.add("C04");
		//viewlist.add("C06");
		viewlist.add("C08");

	}
	
	@Override
	public FormResult doOperation(NmCommandBean nmCommandBean, List<ObjectBean> listBean)
			throws WTException {
		FormResult fromResult = super.doOperation(nmCommandBean, listBean);
		HttpServletRequest request = nmCommandBean.getRequest();
		StringBuilder sb=new StringBuilder("批量转厂信息:\r\n");
		if( request != null ){
			
			 String[] parameter = request.getParameterValues( "fileUrl" );
			 
			 if( parameter == null ){
				 return fromResult;
			 }
			 
			 String textName = parameter[0];
			 
			 if( textName != null ){
				 //判断是否为Excel文件类型
				 if( !textName.endsWith(".xls") && !textName.endsWith( ".xlsx" ) ){
					 throw new WTException("选择的文件必须是Excel格式的文件");
				 }
			 }
			 
			 Map<String, String> map = new HashMap<String, String>();
			 File file = (File) request.getAttribute("fileUrl");
			 
			 if( file != null ){				
				 String fileNumber = file.getAbsolutePath(); 
				 
				 if( fileNumber != null ){
					 FileInputStream fis = null;
					 Workbook wb = null;
					 boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
					 try {
						fis = new FileInputStream(fileNumber);
						 //根据Excel文件的格式判断文件的解释方式为03或07（解析Excel兼容性）
						 if( textName.endsWith(".xls") ){
							 wb = new HSSFWorkbook( fis );
						 }else if( textName.endsWith( ".xlsx" ) ){
							 wb = new XSSFWorkbook( fis );
						 }
						 Sheet sheet = wb.getSheetAt(0);
						 int lastRowNum = sheet.getLastRowNum();	
						 System.out.println("lastRowNum === " + lastRowNum);
							for(int i =1; i<= lastRowNum ; i++){
								Row row = sheet.getRow(i);
								if(! isBlankRow(row)){
									Cell cell0 = row.getCell(0);
									Cell cell= row.getCell(1);
									String cell2 ="";
									String cell1 ="";
									if(!cell0.toString().equals("")){
										 cell1 =getCellValue( cell0);
									}
									if(!cell.toString().equals("")){
										 cell2 =getCellValue( cell);
									}
								
									map.put(cell1,cell2);
								}
							}
					 massTransitFactory(map ,sb);	
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}finally{
						SessionServerHelper.manager.setAccessEnforced( flag );
					}
				 }
			 }
		}
		
		FeedbackMessage feedbackmessage = new FeedbackMessage(FeedbackType.SUCCESS,  SessionHelper.getLocale(),"已执行转视图操作", null, sb.toString() );
		fromResult.addFeedbackMessage(feedbackmessage);
		
		return fromResult;
	}

	public static void massTransitFactory(Map <String ,String> map ,StringBuilder sb) throws WTException, IOException{

		if(map .size() == 0){
			return  ;
		}
		Set<String> keySet = map.keySet();
		Iterator<String> iterator = keySet.iterator();
		while(iterator.hasNext()){
			String number = iterator.next();
			WTPart part = CoreUtil.getWTPartByNumberAndView(number, "Design");
			String factory = map.get(number);
			String[] factorys = {factory};
			if(part == null){
				sb.append("编号为").append(number).append(",视图为Design的物料不存在！<br>");
			}else{
				if(WorkInProgressHelper.isCheckedOut(part)){
					sb.append("编号为").append(number).append("的物料已被检出！<br>");	
				}else{
					View[] views = ViewHelper.service.getAllViews();//获取系统中所有的视图
					List<String> list = new ArrayList<String>();
					for(View view : views){
						String viewName = view.getName();
						list.add(viewName);
					}
					
					if(! list.contains(factory)){
						sb.append("编号为").append(number).append("的物料不存在视图").append(factory).append("，不能进行转换！<br>");
					}else{
						String softTypeInternal = getSoftTypeInternal(part);
						if(softTypeInternal.equals(RAWMATERIAL)){
							if(viewlist.contains(factory)){
								TransitFactoryUtil.tansitPartAndChildrenFactory(part, facs);
								for(int i=0;i<facs.length;i++){
									String fac = facs[i];
									WTPart wtPart = CoreUtil.getWTPartByNumberAndView(part.getNumber(),fac);
									if(wtPart== null){
										sb.append("编号为").append(number).append("的物料转").append(fac).append("视图失败！<br>");
									}else{
										sb.append("编号为").append(number).append("的物料转").append(fac).append("视图成功！<br>");
									}
								}
							}else{
								TransitFactoryUtil.tansitPartAndChildrenFactory(part, factorys);
								WTPart wtPart = CoreUtil.getWTPartByNumberAndView(part.getNumber(), factorys[0]);
								if(wtPart != null){
									sb.append("编号为").append(number).append("的物料转").append(factorys[0]).append("视图成功！<br>");
								}else{
									sb.append("编号为").append(number).append("的物料转").append(factorys[0]).append("视图失败！<br>");
								}
							
							}
						}else{
							TransitFactoryUtil.tansitPartAndChildrenFactory(part, factorys);
							WTPart wtPart = CoreUtil.getWTPartByNumberAndView(part.getNumber(), factorys[0]);
							if(wtPart != null){
								sb.append("编号为").append(number).append("的物料转").append(factorys[0]).append("视图成功！<br>");
							}else{
								sb.append("编号为").append(number).append("的物料转").append(factorys[0]).append("视图失败！<br>");
							}
						}
					}
				}
			}
		}	
		
		System.out.println("sb ===========" + sb.toString());
	}
	
	/**
	 * 转换excel单元格的值
	 * @param cell 获取到的单元格的值
	 * @return value 转换为字符串的单元格的值
	 * @throws WTException 异常
	 */
	public static String getCellValue(Cell cell) throws WTException {
		 String value = "";
		 try {
				if (cell == null) {
					return "";
				}
				switch (cell.getCellType()) {
				case Cell.CELL_TYPE_NUMERIC:
					int b  = (int) cell.getNumericCellValue();
					double a =cell.getNumericCellValue();
					if(b!= 0 && a != 0){
						if(a == b){
							value = Integer.toString(b) ;
						}else{
							value = Double.toString(a) ;
						}
					}
					
					break;
				case Cell.CELL_TYPE_STRING:
					value = cell.getStringCellValue();
					break;
				case Cell.CELL_TYPE_BLANK:
					value = "";
					break;
				case Cell.CELL_TYPE_BOOLEAN:
					value = Boolean.toString(cell.getBooleanCellValue());
					break;
				case Cell.CELL_TYPE_FORMULA:
					try {
						value = String.valueOf((int) cell.getNumericCellValue());
					} catch (Exception e) {
						value = cell.getStringCellValue();
					}
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new WTException(e.getMessage());
			}
			return value;
	 }
	
	/**
	 * 获取对象的软类型
	 * 
	 * @param obj
	 * @return
	 */
	public static  String getSoftTypeInternal( WTObject obj) {
		String internalName = "";
		
		if(obj!=null) {
			try {
				internalName=ClientTypedUtility.getTypeIdentifier(obj).getTypename() ;
				
				if( internalName != null ){
					int startIndex = internalName.lastIndexOf(".") + 1 ;
					internalName = internalName.substring( startIndex ) ;

				}
			} catch(WTException e) {
				e.printStackTrace() ;
			}
		}
		return internalName; 
	}
	
	public static boolean isBlankRow(Row row){
        if(row == null) return true;
        boolean result = true;
        for(int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++){
           Cell cell = row.getCell(i, HSSFRow.RETURN_BLANK_AS_NULL);
            String value = "";
            if(cell != null){
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    value = cell.getStringCellValue();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    value = String.valueOf((int) cell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    value = String.valueOf(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    value = String.valueOf(cell.getCellFormula());
                    break;
                //case Cell.CELL_TYPE_BLANK:
                //    break;
                default:
                    break;
                }
                 
                if(!value.trim().equals("")){
                    result = false;
                    break;
                }
            }
        }
         
        return result;
    }
}
